package com.winner.data.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import javax.annotation.Resource;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.winner.data.entity.request.UserDto;
import com.winner.data.entity.vo.UserResult;
import com.winner.data.exception.R;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * Spring Boot调用外部接口的 3 种方式 方式一：使用原始httpClient请求 方式二：使用RestTemplate方法 方式三：使用Feign进行消费
 *
 * @author wangxinle5
 * @since 2023-06-26
 */
@RestController
@Slf4j
public class RestTemplateController extends BaseController {

    @Resource
    RestTemplate restTemplate;

    RestTemplate unSSLRestTemplate = SpringUtil.getBean("unSSLRestTemplate");

    /**
     */
    @PostMapping("/post")
    public void post() {
        UserDto userDTO = new UserDto();
        List<String> responseList;
        ResponseEntity<UserResult> response = null;
        HttpHeaders headers = new HttpHeaders();
        headers.set("token", "123");
        try {
            // restTemplate.getForObject()方法,不支持带header请求 拿到完整的 HTTP 响应信息，包括状态码、响应头和响应体
            response = restTemplate.exchange("", HttpMethod.POST, new HttpEntity<>(userDTO, headers), UserResult.class);
        } catch (RestClientException e) {
            log.info("POST error, error is {}", e.getMessage());
        }
        Integer code = Optional.ofNullable(response).map(HttpEntity::getBody).map(UserResult::getCode).orElse(null);
        if (Objects.equals(code, 0)) {
            log.info("POST success, Response is {}", response);
            // 拿到响应的数据list
            responseList = response.getBody().getData();
            log.info("POST success, Response data is {}", responseList);
            // 拿到响应的header Objects.equals(getResponse.getStatusCode().value(), HttpStatus.OK.value())
//            HttpHeaders headers = response.getHeaders();
        }

    }

    /**
     * get请求
     *
     * @return 结果
     */
    @GetMapping("/get")
    public R get() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("cookie", "11");
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("");
        HashMap<String, Object> map = new HashMap<>(1);
        map.put("course_id", "123");
        for (Map.Entry<String, Object> e : map.entrySet()) {
            builder.queryParam(e.getKey(), e.getValue());
        }
        String realUrl = builder.toUriString();
        ResponseEntity<UserResult> getResponse = unSSLRestTemplate.exchange(realUrl, HttpMethod.GET,
            new HttpEntity<String>(null, headers), UserResult.class);
        if (Objects.equals(getResponse.getStatusCode().value(), HttpStatus.OK.value())) {

        }
        return R.success();
    }


    /**
     * get请求, url有json需要按该方法请求,否则报错:Not enough variable values available to expand '""'
     *
     * @return 结果
     */
    @GetMapping("/getUrlContainsJson")
    public ResponseEntity<String> getUrlContainsJson() {
        String queryParam = "{\"username\":\"zhangsan\"}";
        String url = "http://localhost:8080/list?query={queryParam}";
        return restTemplate.getForEntity(url, String.class, queryParam);
    }

}
